package com.xzl.xep.exception;

import java.util.HashMap;
import java.util.Map;

public class FormValidationException extends BusinessException {

	private static final long serialVersionUID = 1L;
	
	private Map<String, FormElement> errors;
	

	public class FormElement{
		private String code;
		private Object value;
		private boolean isError;
		private String message;
		
		public FormElement(String code, Object value, String message,boolean error){
			this.code = code;
			this.value = value;
			this.message = message;
			this.isError = error;
		}
		
		public FormElement(String code, Object value, String message){
			this.code = code;
			this.value = value;
			this.message = message;
			this.isError = true;
		}
		
		public String getCode() {
			return code;
		}
		public void setCode(String code) {
			this.code = code;
		}
		public Object getValue() {
			return value;
		}
		public void setValue(Object value) {
			this.value = value;
		}
		public String getMessage() {
			return message;
		}
		public void setMessage(String message) {
			this.message = message;
		}
		public void setError(boolean error){
			this.isError = error;
		}
		public boolean isError(){
			return this.isError;
		}
		
	}
	

	public FormValidationException(){
		super();
		errors = new HashMap<String,FormElement>();
	}
	
	public void addFiled(String code,Object value){
		if(errors == null) errors =  new HashMap<String,FormElement>();
		
		errors.put(code, new FormElement(code,value,"",false));
		
	}
	
	public void addError(String code,Object value,String message){
		if(errors == null) errors =  new HashMap<String,FormElement>();
		if(errors.containsKey(code)){
			this.setError(code,message);
		}else{
			errors.put(code, new FormElement(code,value,message));
		}
		
	}
	
	public void setError(String code, String message){
		errors.get(code).setError(true);
		errors.get(code).setMessage(message);
	}
	
	public Map<String,FormElement> getErrors(){
		return errors;
	}
	
	public boolean hasError(String code){
		if(errors !=null && errors.size() >0){
			if(errors.containsKey(code) &&  errors.get(code).isError)return true;
			else return false;
		}
		return false;
	}
	
	public String getErrorMessage(String code){
		return errors.get(code).getMessage();
	}
	
	public Object getErrorValue(String code){
		return errors.get(code).getValue();
	}
	
	public boolean hasError(){
		if(errors !=null ){
			for(String key : errors.keySet()){
				if(errors.get(key).isError()) return true;
			}
		}
		return false;
	}



	@Override
	public String toJsonStr() {
		return super.toJsonStr();
	}
	
	
}
